package com.example.ymm.modules1.controller.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.example.ymm.model.CommonResult;
import com.example.ymm.modules1.controller.BaseController;
import com.example.ymm.modules1.service.dto.common.ExcelData;
import com.example.ymm.modules1.service.dto.common.ExcelDataListener;
import com.example.ymm.modules1.service.dto.heng.ex.ImQuestionGroupDto;
import com.example.ymm.modules1.service.hl.ex.ExQuestionService;
import com.example.ymm.util.ArrayListSplitter;
import com.example.ymm.util.DateKit;

import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/hl/excel")
@Tag(name = "excel管理")
@Slf4j
public class ExcelController extends BaseController {

    @Autowired
    ExQuestionService exQuestionService;


    @Schema( name =  "题目导入")
    @PostMapping("/importExcelQuestion")
    public CommonResult importExcelQuestion(@RequestParam("file") MultipartFile file) {
        try{
//            System.out.println(dto);
//            ExcelUtils.readExcelFile(file);

            ExcelDataListener excelDataListener = new ExcelDataListener();
            try (InputStream inputStream1 = file.getInputStream()) {

                // EasyExcel 读取文件中的内容
                EasyExcel.read(inputStream1, ExcelData.class, excelDataListener).excelType(ExcelTypeEnum.XLSX).sheet().doRead();

                // 使用 Apache POI 读取图片
                InputStream inputStream = file.getInputStream();
                Workbook workbook = new XSSFWorkbook(inputStream);
                Sheet sheet = workbook.getSheetAt(0);
                Map<Integer, Map<Integer, PictureData>> pictureMap = getPictures(sheet);
                List<ExcelData> dataList = excelDataListener.getDataList();

                List<List<ExcelData>> lists = ArrayListSplitter.extractSubArrays(dataList);

                List<ImQuestionGroupDto> list=new ArrayList<>();
                for (List<ExcelData> list1 : lists) {
                    ImQuestionGroupDto imDto = new ImQuestionGroupDto();
                    Integer rowId = list1.get(1).getRowId();
                    imDto.setRowId(rowId);
                    imDto.setItems(list1);
                    list.add(imDto);
                }

                Map<Integer, ExcelData> map = dataList.stream().collect(Collectors.toMap(ExcelData::getRowId, Function.identity()));
                // 将easyexcel读到的数据和图片进行匹配，如果有云存储 阿里云、者华为云或者minio，可以将文件上传后，把上传后的文件地址和数据匹配。
                for (Map.Entry<Integer, ExcelData> dataEntry : map.entrySet()) {
                    Integer rowId = dataEntry.getKey();
                    ExcelData excelData = dataEntry.getValue();

                    if (pictureMap.containsKey(rowId)) {
//                        System.out.println("--数据:"+excelData);
                        Map<Integer, PictureData> integerPictureDataMap = pictureMap.get(dataEntry.getKey());
                        List<String> imgArr=new ArrayList<>();
                        for (Map.Entry<Integer, PictureData> pictureDataEntry : integerPictureDataMap.entrySet()) {
                            int colId = pictureDataEntry.getKey();
                            PictureData pictureData = pictureDataEntry.getValue();
                            byte[] pictureBytes = pictureData.getData();
                            /**
                             * 保存文件
                             */
                            String month = DateKit.dateFormat(new Date(), "yyyy-MM");
                            String dates =month+"/"+ DateKit.dateFormat(new Date(), "yyyy-MM-dd");
                            String result = null;
                            String path = "app_file/images/";
                            String savePath = com.example.ymm.util.FileUtil.domian + path;
                            String fileName=IdUtil.getSnowflake().nextIdStr() + rowId + "-" + colId + getImageSuffix(pictureData);
                            savePath += dates + "/" + fileName;
                            result = com.example.ymm.util.FileUtil.host + path + dates + "/" + fileName;
                            imgArr.add(result);
//                            System.out.println("---savePath:"+savePath);
                            File targetFile = new File(savePath);
                            File file1 = FileUtil.writeBytes(pictureBytes, targetFile);
//                            System.out.println(file1);
                            // 组装数据，可以保存到对应的数据源中
//                            System.out.println("data row " + rowId + " ExcelData data " + dataEntry.getValue() + " Picture in row " + rowId + " col index " + colId + " size: " + pictureBytes.length);
                        }
                        for (ImQuestionGroupDto  groupDto:list){
                            if(groupDto.getRowId()==rowId){
                                groupDto.setImg(String.join(",", imgArr));
                            }
                        }
                    }
                }
//                System.out.println(list.size());
                List<String> msgs=new ArrayList<>();
                msgs =exQuestionService.importQuestionFn3(list);
                return CommonResult.success(msgs);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }catch (Exception e){
            log.error(e.getMessage(),e);
            return CommonResult.error(e.getMessage());
        }
    }


    // 根据文件头信息，得到对应的文件后缀名，文件类型提供13+种，下面罗列了一些常用的文件后缀名
    private static String getImageSuffix(PictureData pictureData) {
        int pictureType = pictureData.getPictureType();
        switch (pictureType) {
            case Workbook.PICTURE_TYPE_JPEG:
                return ".jpg";
            case Workbook.PICTURE_TYPE_PNG:
                return ".png";
            case Workbook.PICTURE_TYPE_DIB:
                return ".dib";
            case XSSFWorkbook.PICTURE_TYPE_GIF:
                return ".gif";
            case Workbook.PICTURE_TYPE_EMF:
                return ".emf";
            case Workbook.PICTURE_TYPE_WMF:
                return ".wmf";
            case Workbook.PICTURE_TYPE_PICT:
                return ".pict";
            case XSSFWorkbook.PICTURE_TYPE_WPG:
                return ".wpg";
            case XSSFWorkbook.PICTURE_TYPE_TIFF:
                return ".tif";
            case XSSFWorkbook.PICTURE_TYPE_EPS:
                return ".eps";
            case XSSFWorkbook.PICTURE_TYPE_BMP:
                return ".bmp";
            default:
                return "未知后缀名";
        }
    }

    // 处理图片
    // 放回结果格式说明：Map<行号,Map<列号，PictureData对象>>
    private Map<Integer, Map<Integer, PictureData>> getPictures(Sheet sheet) {
        Map<Integer, Map<Integer, PictureData>> pictureMap = new HashMap<>();
        Drawing<?> drawing = sheet.getDrawingPatriarch();
        if (drawing == null) {
            drawing = sheet.createDrawingPatriarch();
        }
        int sort=0;
        if (drawing instanceof XSSFDrawing ) {
            XSSFDrawing xssfDrawing= (XSSFDrawing) drawing;
            for (XSSFShape shape : xssfDrawing.getShapes()) {
                if (shape instanceof XSSFPicture) {
                    XSSFPicture picture= (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getClientAnchor();
                    int row = anchor.getRow1();
                    short col = anchor.getCol1();
                    sort++;
                    System.out.println("row " + row + " col " + col);
                    PictureData pictureData = picture.getPictureData();
                    if (pictureMap.containsKey(row)) {
                        Map<Integer, PictureData> integerPictureDataMap = pictureMap.get(row);
                        integerPictureDataMap.put((int) sort, pictureData);
                        pictureMap.put(row, integerPictureDataMap);
                    } else {
                        Map<Integer, PictureData> pictureSubMap = new HashMap<>();
                        pictureSubMap.put((int) col, pictureData);
                        pictureMap.put(row, pictureSubMap);
                    }
                }
            }
        }
        return pictureMap;
    }


}
